#include "Threadpool.h"
#include <unistd.h>
Threadpool::Threadpool(int threadNum,int queSize)
:_threads()
,_threadNum(threadNum)
,_queSize(queSize)
,_que(queSize)
,_isExit(false){
    _threads.reserve(_threadNum);
}

void Threadpool::start(){
    for(int i =0; i<_threadNum;++i){
        unique_ptr<Thread> up(new Thread(std::bind(&Threadpool::doTask,this)));
        _threads.push_back(std::move(up));
    }
    for(auto &thread:_threads){
        thread->start();
    }
}
void Threadpool::stop(){
    while(!_que.empty()){
        //当任务队列不为空的时候休眠
        sleep(1);
    }
    _isExit = true;
    _que.wakeup();
    for(auto&thread:_threads){
        thread->join();
    }
}
void Threadpool::addTask(Task &&task){
      if(task){
        _que.push(std::move(task));
      }
}
void Threadpool::doTask(){
     while (!_isExit)
     {
        Task tmp = _que.pop();
        if(tmp){
            tmp();
        }
     }
     
}